package uk.gov.swmprobation.cplite;

import java.io.File;
import java.util.ArrayList;

import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CreateProject extends MyActivity {
	
	private MyOpenViewMap myOpenMapView;
	private MapController myMapController;
	private GeoPoint point;
	private Project project;
	
	static WifiManager wifi;
	BroadcastReceiver receiver;
	private GestureDetector gestureDetector;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Show Hint each time until setting changed
		if (sharedPref.getBoolean(SettingsActivity.submitHintTitle, true)){
			Helper.showHintDialog(this, SettingsActivity.submitHintTitle, SettingsActivity.submitHintMessage);
		}
		setContentView(R.layout.activity_create_project);
		
		gestureDetector = new GestureDetector(this, new MyGestureDetector());
		
		initVariables();
				
		ImageView photo = (ImageView) findViewById(R.id.photo);
		int max_photo_size = sharedPref.getInt("Max_Picture_Size", 200);
		Bitmap photoBitmap = PhotoTools.fitBitmapIn(project.getImagePath(), max_photo_size);
		if (photoBitmap!=null)	{
			photo.setImageBitmap(photoBitmap);
			photo.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setAction(android.content.Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(new File(project.getImagePath())), "image/jpg");
					startActivity(intent);
				}
    			
    		});
		}
        myOpenMapView.setBuiltInZoomControls(false);
        myOpenMapView.setOnTouchListener(mapTouchListener);
        myMapController.setZoom(19);
        myMapController.setCenter(point);
        myOpenMapView.allowScroll=true;
        myOpenMapView.allowZoom=false;
        addMarker();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.create_project, menu);
		if (!PhotoTools.photoExists(project.getImagePath())){
			MenuItem menuItem = menu.findItem(R.id.action_send);
			menuItem.setEnabled(false);
			menuItem.getIcon().setAlpha(50);
			((TextView)findViewById(R.id.touchinstruction)).setText("Photo can not be found check SD Card");
		}
		return true;
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_delete:
            	final int localId = project.getId();

                Project projectToDelete = DatabaseHandler.getProject(localId);
                
                final String projectName = projectToDelete.getProjectName();
                
        		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        		builder.setMessage("Are you sure you want to delete "+projectName+"?");
        	    builder.setTitle("Delete project?");
        		builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        		           public void onClick(DialogInterface dialog, int id) {
        		        	   DatabaseHandler.deleteProject(localId);
        		        	   finish();
        		           }
        		       });
        		builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
        		           public void onClick(DialogInterface dialog, int id) {
        		           }
        		       });

        		AlertDialog dialog = builder.create();
        		dialog.show();
                return true;
            case R.id.action_send:
            	if(sharedPref.getString("user_email", "").length()<6){
       				AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
       				builder2.setMessage("Can we take an e-mail address so we can contact you about your project?");
       				builder2.setTitle("Contact address?");
       				builder2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
       				           public void onClick(DialogInterface dialog, int id) {
       				        	   Intent openSettings = new Intent(CreateProject.this, SettingsActivity.class);
       				        	   startActivity(openSettings);
       				           }
       				       });
       				builder2.setNegativeButton("No", new DialogInterface.OnClickListener() {
       				           public void onClick(DialogInterface dialog, int id) {
       				        	   checkWifi();
       				           }
       				       });

       				AlertDialog dialog2 = builder2.create();
       				dialog2.show();
            	} else {
            		checkWifi();
            	}
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
	
	private void initVariables(){
		Bundle extras = getIntent().getExtras();
		int id = extras.getInt("id");
		project = DatabaseHandler.getProject(id);
		myOpenMapView = (MyOpenViewMap)findViewById(R.id.openmapview);
		myMapController = myOpenMapView.getController();
        point = new GeoPoint(project.getLat(), project.getLng());
	}

	private OnTouchListener mapTouchListener = new OnTouchListener(){

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			return gestureDetector.onTouchEvent(event);
		}};
	
	private void addMarker(){
		Drawable markerImage=getResources().getDrawable(R.drawable.markergreen);
        
        markerImage.setBounds(0, 0, markerImage.getIntrinsicWidth(),
                                markerImage.getIntrinsicHeight());
        
        ArrayList<OverlayItem> markerItems = new ArrayList<OverlayItem>();
        
        OverlayItem markerItem = new OverlayItem("Location", "Location of Picture", point);
        markerItem.setMarker(markerImage);
        
        markerItems.add(markerItem);
        
        ItemizedIconOverlay<OverlayItem> markerOverlay = new ItemizedIconOverlay<OverlayItem>(this, markerItems, null){
        	public boolean onFling(android.view.MotionEvent pEvent1,
                    android.view.MotionEvent pEvent2,
                    float pVelocityX,
                    float pVelocityY,
                    MapView pMapView){
						return true;
        		
        	}
        };

        myOpenMapView.getOverlays().add(markerOverlay);
	}

	private void checkWifi(){
		PhotoTools.saveThumbnail(project);
			if(Helper.checkWifi()){
				//If Wifi is available send straight away
				sendNow(project.getId());
			} else {
				//If not send as per users setting
				int wifiCode = Integer.parseInt(sharedPref.getString("pref_wait_wifi", "2"));
				switch (wifiCode){
					case 1:
						delaySending();
						break;
					case 2:
						View checkBoxView = View.inflate(this, R.layout.save_setting, null);
						final CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.savesettingcheck);
						AlertDialog.Builder builder = new AlertDialog.Builder(this);
						builder.setMessage("Would you like to send now anyway?");
					    builder.setTitle("Wifi not available");
					    builder.setView(checkBoxView);
						builder.setPositiveButton("Send Now", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						        	   if (checkBox.isChecked()){
						        		   sharedPref.edit().putString("pref_wait_wifi","3").commit();
						        	   }
						        	   sendNow(project.getId());
						           }
						       });
						builder.setNegativeButton("Wait for Wifi", new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						        	   if (checkBox.isChecked()){
						        		   sharedPref.edit().putString("pref_wait_wifi","1").commit();
						        	   }
						        	   delaySending();
						           }
						       });
	
						AlertDialog dialog = builder.create();
						dialog.show();
						break;
					case 3:
						sendNow(project.getId());
						break;
					default:
						
				}	
			}
	}
	
	private void sendNow(int localId){
		project.setProjectStatus("Waiting");
		project.save();
		Intent serviceIntent = new Intent(this, SendWaiting.class);
		serviceIntent.putExtra("localId", localId);
		this.startService(serviceIntent);
		finish();
	}
	
	private void delaySending(){
		project.setProjectStatus("Waiting");
		project.save();
		finish();
	}

	class MyGestureDetector extends GestureDetector.SimpleOnGestureListener
	{

	@Override
	 public boolean onDoubleTap(MotionEvent event)
	 {
	    Projection projection = myOpenMapView.getProjection();
    	point = (GeoPoint) projection.fromPixels(event.getX(), event.getY());
    	project.setLat(point.getLatitudeE6()/1000000.0);
        project.setLng(point.getLongitudeE6()/1000000.0);
        myOpenMapView.getOverlays().clear();
        addMarker();
        myOpenMapView.invalidate();
	    return true;
	 }

	}
}
